package com.chao.common.config.mybatis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chao.common.config.mybatis.PageSortHelper;
import com.chao.common.util.reaction.PageList;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * mysql 拦截器处理
 */
public class LogSqlHelper {

    private static final Logger log = LoggerFactory.getLogger(LogSqlHelper.class);

    private static final String PATTERN = "yyyy-MM-dd HH:mm:ss";

    public LogSqlHelper() {
    }

    /**
     * 拦截器入口
     */
    public static Object intercept(Invocation invocation) throws Throwable {
        long startTime = System.currentTimeMillis();
        String sql = formatSql(invocation);
        //执行查询
        String methodName = invocation.getMethod().getName();
        Object returnValue;
        try {
            if ("query".equals(methodName)) {
                returnValue = selectSql(invocation);
            } else {
                returnValue = invocation.proceed();
            }
        } catch (InvocationTargetException e) {
            throw e;
        }
        //记录sql执行时长
        long cost = System.currentTimeMillis() - startTime;
        log.debug("cost = {} ms, affected rows = {}, SQL: {}", cost, formatResult(returnValue), sql);
        return returnValue;
    }

    /**
     * 格式化返回值
     */
    private static String formatResult(Object obj) {
        String str = JSON.toJSONString(obj);
        if(str.length() > 300){
            return str.substring(0,300);
        }
        return str;
    }

    /**
     * 拦截查询sql  封装分页
     */
    private static Object selectSql(Invocation invocation) throws Throwable {
        //解析sql
        final Object[] queryArgs = invocation.getArgs();
        MappedStatement mappedStatement = (MappedStatement) queryArgs[0];
        Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = queryArgs[1];
        }
        //获取sql语句
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();
        //获取入参对象
        Object parameterObject = boundSql.getParameterObject();
        //如果无入参 则直接查询并返回结果
        if (null == parameterObject) {
            return invocation.proceed();
        }
        //解析入参对象的值
        MetaObject metaObject = configuration.newMetaObject(parameterObject);
        JSONObject json = isPage(metaObject.getOriginalObject());
        // json为null则表示不需要分页 不为null则表示为分页查询
        if(null != json){
            //封装分页查询
            String sql = com.chao.common.config.mybatis.PageSortHelper.removeSqlSemicolon(boundSql.getSql().trim());
            //查询记录总条数
            final int total = com.chao.common.config.mybatis.PageSortHelper.queryTotal(sql, mappedStatement, boundSql);

            //查询分页列表
            queryArgs[2] = new RowBounds(RowBounds.NO_ROW_OFFSET, RowBounds.NO_ROW_LIMIT);
            queryArgs[0] = PageSortHelper.copyFromNewSql(mappedStatement, boundSql, sql,json);
            List<Object> ret = (List<Object>) invocation.proceed();
            PageList<Object> pageList = new PageList<>(total, ret);
            List<PageList<?>> result = new ArrayList<>(1);
            result.add(pageList);
            return result;
        }else{
            //执行sql
            Object ret = invocation.proceed();
            //判断返回结果为列表 则将结果封装成PageList对象返回
            if(ret instanceof Collection){
                String str = mappedStatement.getId();
                String className = str.substring(0,str.lastIndexOf("."));
                String methodName = str.substring(str.lastIndexOf(".")+1);
                Class<?> classObj = Class.forName(className);
                Method[] methods =  classObj.getMethods();
                for (Method method : methods) {
                    if (methodName.equals(method.getName()) && method.getReturnType().equals(PageList.class)) {
                        List<Object> list = (List<Object>) ret;
                        PageList<Object> pageList = new PageList<>(list.size(), list);
                        List<PageList<?>> result = new ArrayList<>(1);
                        result.add(pageList);
                        return result;
                    }
                }
            }
            return ret;
        }

    }

    /**
     * 判断当前请求是否分页请求
     */
    private static JSONObject isPage(Object obj) {
        if (obj instanceof Map) {
            Map map = (Map) obj;
            for (Object key : map.keySet()) {
                if (map.get(key) instanceof JSONObject) {
                    JSONObject json = (JSONObject) map.get(key);
                    if (json.containsKey("page") && json.containsKey("size")) {
                        return json;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 解析sql入参  用于日志记录
     */
    private static String formatSql(Invocation invocation) {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }

        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.substring(0,sql.indexOf("?"))+formatParameterValue(parameterObject) + sql.substring(sql.indexOf("?")+1);
            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    Object obj;
                    if (metaObject.hasGetter(propertyName)) {
                        obj = metaObject.getValue(propertyName);
                        sql = sql.substring(0,sql.indexOf("?"))+formatParameterValue(obj) + sql.substring(sql.indexOf("?")+1);
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.substring(0,sql.indexOf("?"))+formatParameterValue(obj) + sql.substring(sql.indexOf("?")+1);
                    }
                }
            }
        }
        return sql;
    }

    /**
     * 格式化入参
     */
    private static String formatParameterValue(Object obj) {
        if (obj == null) {
            return "NULL";
        } else {
            String value = obj.toString();
            if (obj instanceof Date) {
                DateFormat dateFormat = new SimpleDateFormat(PATTERN);
                value = dateFormat.format((Date) obj);
            }
            if (!(obj instanceof Number) && !(obj instanceof Boolean)) {
                value = "'" + value + "'";
            }
            return value;
        }
    }
}